import React, { useEffect, useState } from "react";
import styles from "./index.module.css";
import http from "../../utils/http";
import { Search, Toast } from "react-vant";
interface CommonData {
  restorativesid: string;
  restorativestitle: string;
  restorativesprice: number;
  restorativesname: string;
  restorativesstate: string;
  restorativesimage: string;
}
const Index: React.FC = () => {
  const [commonData, setCommonData] = useState([] as CommonData[]);
  const [pageCode, setPageCode] = useState(1);
  const [pageSize] = useState(10);
  const [value, setValue] = useState("");
  const [priceSortOrder, setPriceSortOrder] = useState<"asc" | "desc" | null>(
    null
  );
  const [prevPriceSortOrder, setPrevPriceSortOrder] = useState<
    "asc" | "desc" | null
  >(null);
  const [searchHints, setSearchHints] = useState<string[]>([]); // 用于存储搜索提示信息

  const getlist = async () => {
    let params = {
      pageCode: pageCode,
      pageSize: pageSize,
      search: value,
    };
    if (priceSortOrder) {
      params = {
        ...params,
        sortBy: "price",
        sortOrder: priceSortOrder,
      };
    }
    const res = await http.get("/restorative/list", { params });
    if (res.data.code === 200) {
      let sortedData = res.data.data;
      if (priceSortOrder === "asc") {
        sortedData = sortedData.sort(
          (a, b) => a.restorativesprice - b.restorativesprice
        );
      } else if (priceSortOrder === "desc") {
        sortedData = sortedData.sort(
          (a, b) => b.restorativesprice - a.restorativesprice
        );
      }
      setCommonData(sortedData);
    } else if (res.data.code === 404) {
      Toast.info("未找到符合条件的数据，请检查关键词是否准确");
    } else {
      Toast.fail(`搜索出现问题，错误码：${res.data.code}`);
    }
  };
  useEffect(() => {
    // console.log('sortOrder 发生变化，当前值为：', sortOrder);
    setPageCode(1);
    setCommonData([]);
  }, []);
  useEffect(() => {
    getlist();
  }, [pageCode, pageSize, value, priceSortOrder]);

  const handleSearchClick = () => {
    const keyword = value.trim();
    if (keyword.length > 50) {
      Toast.info("搜索关键词过长，请重新输入");
      return;
    }
    setSearchHints([]); // 发起正式搜索时清空提示信息
    setPageCode(1);
    setCommonData([]);
    getlist();
  };

  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.keyCode === 13) {
      handleSearchClick();
    }
  };
  const handlePriceSortClick = () => {
    if (priceSortOrder === null) {
      // 从未排序状态切换到降序排序（默认第一次点击按价格从高到低排序）
      setPriceSortOrder("desc");
    } else if (priceSortOrder === "desc") {
      // 从降序切换到升序
      setPriceSortOrder("asc");
    } else {
      // 从升序切换回默认无排序状态
      setPriceSortOrder(null);
    }
    // 更新上一次的排序顺序状态
    setPrevPriceSortOrder(() => priceSortOrder);
    // 重置页码为1，准备重新加载排序后的数据
    setPageCode(1);
    // 清空已加载的数据
    setCommonData([]);

    setTimeout(() => {
      console.log("After state updates, checking commonData:", commonData);
    }, 1000); // 延迟1秒后打印，查看此时数据状态
  };
  return (
    <div className={styles.commonDatabox}>
      {/* 搜索 */}
      <div className={styles.search}>
        <Search
          value={value}
          onChange={(newValue) => {
            setValue(newValue);
          }}
          placeholder="请输入搜索关键词"
          onKeyDown={handleKeyDown}
          className={styles.input}
        />
        <button className={styles.btn}>搜索</button>
        {/* {searchHints.length > 0 && (
          <div className={styles.searchhints}>
            {searchHints.map((hint, index) => (
              <div key={index}>{hint}</div>
            ))}
          </div>
        )} */}
      </div>
      {/* 升降序 筛选 */}
      <div className={styles.commonDataboxsort}>
        <span onClick={handlePriceSortClick}>价格</span>
        <span>销量</span>
      </div>
      {/* 数据 */}
      <div className={styles.commonDataboxdata}>
        <div className={styles.searchresultcount}>
          共找到 {commonData.length} 条结果
        </div>
        {commonData.map((item: CommonData, index: number) => (
          <div key={index} className={styles.commonDataboxdatalist}>
            <div style={{ width: "40%", height: "100%", float: "left" }}>
              <img
                style={{ width: "76%", height: "100%" }}
                src={item.restorativesimage}
                alt=""
              />
            </div>
            <div className={styles.commonDataboxdatalistcontent}>
              <div>标题：{item.restorativestitle}</div>
              <div>价格：{item.restorativesprice}元</div>
              <div>姓名：{item.restorativesname}</div>
              <div>描述：{item.restorativesstate}</div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

export default Index;
